package cn.spream.jstudy.thread;

import java.util.Random;
import java.util.concurrent.BrokenBarrierException;
import java.util.concurrent.CyclicBarrier;

/**
 * Created with IntelliJ IDEA.
 * User: sjx
 * Date: 14-7-1
 * Time: 下午3:37
 * To change this template use File | Settings | File Templates.
 */
public class CyclicBarrierWorker extends Thread {

    private String name;
    private CyclicBarrier cyclicBarrier;
    private Random random = new Random();

    public CyclicBarrierWorker(String name, CyclicBarrier cyclicBarrier) {
        this.name = name;
        this.cyclicBarrier = cyclicBarrier;
    }

    @Override
    public void run() {
        try {
            System.out.println(String.format("[%s]开始闯关", name));
            long time = random.nextInt(5) * 1000;
            Thread.sleep(time);
            System.out.println(String.format("[%s]闯关结束，共耗时%d毫秒", name, time));
            System.out.println(String.format("[%s]等待其他人闯关结束", name));
            cyclicBarrier.await();
            System.out.println(String.format("[%s]开始领奖品", name));
        } catch (InterruptedException e) {
            e.printStackTrace();  //To change body of catch statement use File | Settings | File Templates.
        } catch (BrokenBarrierException e) {
            e.printStackTrace();  //To change body of catch statement use File | Settings | File Templates.
        }
    }

}
